const { adminModel } = require('../../models/admin')

const { setToken } = require('../../utils/jwt')
const { md5 } = require('../../utils/md5')

module.exports = class User {
  // 添加管理员
  static async addAdmin(ctx) {
    let {name, username, password ,avatar} = ctx.request.body

    if (!username || !password) {
      ctx.body = { code: 300, msg: '有未填写项' }
      return
    }

    let data = await adminModel.insertMany({ name,username, password: md5(password) ,avatar})

    if (data.length) ctx.body = { code: 200, msg: '添加成功', data }
    else ctx.body = { code: 400, msg: '添加失败' }
  }
  // 管理员登录
  static async loginAdmin(ctx) {
    let { username, password } = ctx.request.body

    if (!username || !password) {
      ctx.body = { code: 300, msg: '有未填写项' }
      return
    }

    let bool = await adminModel.find({ username })
    if (bool.length) {

      if (bool[0].password === md5(password)) {
        // 设置token
        let token = setToken(bool[0].username);
        ctx.body = {
          code: 200,
          msg: '登录成功',
          data: { token }
        }
      } else {
        ctx.body = { code: 403, msg: '密码错误' }
      }
    } else {
      ctx.body = { code: 400, msg: '管理员不存在' }
    }
  }
  // 管理员信息
  static async getAdmin(ctx) {
    let username = ctx.username
    let data = await adminModel.find({ username }, { name: 1, avatar: 1, username: 1, _id: 0 })
    ctx.body = {
      code: 200,
      msg: '获取成功',
      data: {
        roles: [data[0].username],
        name: data[0].name,
        avatar: data[0].avatar,
        introduction: "是个很人"
      },
    }
  }
  // 修改管理员信息
  static async updateAdmin(ctx) {
    let { name, username, password ,avatar} = ctx.request.body;
    let data = await adminModel.find({ username });
    if (data.length) {
      let id = data[0]._id;
      let bool = await adminModel.updateOne({ _id: id }, {$set:{name, username, password:md5(password) ,avatar}})
      if (bool.n && bool.ok)
        ctx.body = {code:200,msg:'修改成功'}
      else
        ctx.body = {code:400,msg:'修改失败'}
    } else {
      ctx.body = {code:403,msg:'找不到管理员'}
    }
  }
  // 登出
  static async logout(ctx) {
    ctx.body = { code: 200,msg:'登出成功'}
  }
}